// src/page/UserPage.tsx
import React, { useContext, useEffect, useState, useCallback } from 'react';
import {
    Table,
    Button,
    Typography,
    Spin,
    Space,
    Card,
    Row,
    Col,
    Alert,
    Tag,
    Modal,
    message,
    Transfer
} from 'antd';
import {
    DeleteOutlined,
    EditOutlined,
    PlusOutlined,
    UsergroupAddOutlined,
    SafetyCertificateOutlined
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import UserContext from '../context/UserContext';
import type { User } from "../api/service/UserService.tsx";
import SysAuthContext from '../context/SysAuthContext';

const { Title } = Typography;
const { confirm } = Modal;

const UserPage: React.FC = () => {
    const context = useContext(UserContext);
    const authContext = useContext(SysAuthContext);
    const navigate = useNavigate();
    const [bindRoleModalVisible, setBindRoleModalVisible] = useState(false);
    const [bindAuthorityModalVisible, setBindAuthorityModalVisible] = useState(false);
    const [selectedUser, setSelectedUser] = useState<User | null>(null);
    const [userRoles, setUserRoles] = useState<string[]>([]);
    const [userAuthorities, setUserAuthorities] = useState<string[]>([]);

    if (!context) {
        throw new Error('UserPage must be used within UserProvider');
    }

    if (!authContext) {
        throw new Error('UserPage must be used within SysAuthProvider');
    }

    const {
        users,
        loadingUsers,
        error,
        fetchUsers,
        updateUserStatus,
    } = context;

    const {
        roles,
        authorities,
        fetchRoles,
        fetchAuthorities,
        bindUserRoles,
        bindUserAuthorities
    } = authContext;

    // 使用 useCallback 优化函数，避免不必要的重新渲染
    const loadData = useCallback(async () => {
        try {
            // 使用 Promise.all 并行加载数据，提高效率
            await Promise.all([
                fetchUsers(),
                fetchRoles(),
                fetchAuthorities()
            ]);
        } catch (err) {
            console.error('加载数据失败:', err);
        }
    }, [fetchUsers, fetchRoles, fetchAuthorities]);

    // 组件挂载时获取数据，只执行一次
    useEffect(() => {
        loadData();
    }, [loadData]);

    // 替换现有的 toggleUserStatus 函数
    const showConfirm = (userId: string, currentStatus: User['status']) => {
        const targetStatus = currentStatus === 'active' ? 'inactive' : 'active';
        const actionText = targetStatus === 'active' ? '启用' : '冻结';

        confirm({
            title: `确认${actionText}`,
            content: `确定要${actionText}这个账号吗？`,
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                try {
                    const success = await updateUserStatus(userId, targetStatus);
                    if (success) {
                        message.success(`${actionText}用户成功`);
                    } else {
                        message.error(`${actionText}用户失败`);
                    }
                    return success;
                } catch (error) {
                    message.error('操作失败');
                    console.error('Failed to update user status:', error);
                    return false;
                }
            },
        });
    };

    // 处理绑定角色
    const handleBindRoles = async (user: User) => {
        setSelectedUser(user);
        // 获取用户当前角色 - 这里应该从用户对象中获取当前角色，而不是所有角色
        try {
            // 假设用户对象中有 roles 字段包含用户当前的角色
            const currentUserRoleIds = user.roles?.map((role: { id: string }) => role.id) || [];
            setUserRoles(currentUserRoleIds);
            setBindRoleModalVisible(true);
        } catch (error) {
            message.error('获取用户角色信息失败');
            console.error('获取用户角色信息失败:', error);
        }
    };

    // 处理绑定权限
    const handleBindAuthorities = async (user: User) => {
        setSelectedUser(user);
        // 获取用户当前权限 - 这里应该从用户对象中获取当前权限，而不是所有权限
        try {
            // 假设用户对象中有 authorities 字段包含用户当前的权限
            const currentUserAuthorityIds = user.authorities?.map((auth: { id: string }) => auth.id) || [];
            setUserAuthorities(currentUserAuthorityIds);
            setBindAuthorityModalVisible(true);
        } catch (error) {
            message.error('获取用户权限信息失败');
            console.error('获取用户权限信息失败:', error);
        }
    };

    // 保存用户角色绑定
    const handleSaveUserRoles = async () => {
        if (!selectedUser) return;

        try {
            const input = {
                userId: selectedUser.id,
                roleIds: userRoles
            };

            const success = await bindUserRoles(input);
            if (success) {
                message.success('角色绑定成功');
                setBindRoleModalVisible(false);
                // 刷新用户列表以显示最新数据
                await fetchUsers();
            } else {
                message.error('角色绑定失败');
            }
        } catch (error) {
            message.error('角色绑定失败');
            console.error('角色绑定失败:', error);
        }
    };

    // 保存用户权限绑定
    const handleSaveUserAuthorities = async () => {
        if (!selectedUser) return;

        try {
            const input = {
                userId: selectedUser.id,
                authorityIds: userAuthorities
            };

            const success = await bindUserAuthorities(input);
            if (success) {
                message.success('权限绑定成功');
                setBindAuthorityModalVisible(false);
                // 刷新用户列表以显示最新数据
                await fetchUsers();
            } else {
                message.error('权限绑定失败');
            }
        } catch (error) {
            message.error('权限绑定失败');
            console.error('权限绑定失败:', error);
        }
    };

    const handleRoleTransferChange = (targetKeys: React.Key[]) => {
        setUserRoles(targetKeys as string[]);
    };

    const handleAuthorityTransferChange = (targetKeys: React.Key[]) => {
        setUserAuthorities(targetKeys as string[]);
    };

    const userColumns = [
        {
            title: '用户ID',
            dataIndex: 'id',
            key: 'id',
            width: 100,
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '昵称',
            dataIndex: 'nickname',
            key: 'nickname',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: string) => (
                <Tag color={status === 'active' ? 'green' : 'red'}>
                    {status === 'active' ? '启用' : '冻结'}
                </Tag>
            )
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (date: string) => new Date(date).toLocaleString(),
            width: 180,
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (date: string) => new Date(date).toLocaleString(),
            width: 180,
        },
        {
            title: '操作',
            key: 'action',
            width: 250,
            render: (_: unknown, record: User) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<UsergroupAddOutlined />}
                        size="small"
                        onClick={() => handleBindRoles(record)}
                    >
                        绑定角色
                    </Button>
                    <Button
                        type="link"
                        icon={<SafetyCertificateOutlined />}
                        size="small"
                        onClick={() => handleBindAuthorities(record)}
                    >
                        绑定权限
                    </Button>
                    {record.status === 'active' ? (
                        <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                            size="small"
                            onClick={() => showConfirm(record.id, record.status)}
                        >
                            冻结
                        </Button>
                    ) : (
                        <Button
                            type="link"
                            icon={<EditOutlined />}
                            size="small"
                            onClick={() => showConfirm(record.id, record.status)}
                        >
                            启用
                        </Button>
                    )}
                </Space>
            ),
        },
    ];

    // 角色转移数据源
    const roleTransferDataSource = roles.map(role => ({
        key: role.id,
        title: `${role.roleName}`,
    }));

    // 权限转移数据源
    const authorityTransferDataSource = authorities.map(authority => ({
        key: authority.id,
        title: `${authority.authorityName}`,
    }));

    return (
        <div style={{
            height: 'calc(100vh - 112px)',
            overflowY: 'auto',
            scrollbarWidth: 'thin',
            scrollbarColor: '#c1c1c1 #f1f1f1'
        }}>
            <style>
                {`
                /* Webkit浏览器滚动条样式 */
                div::-webkit-scrollbar {
                    width: 4px;
                }
                
                div::-webkit-scrollbar-track {
                    background: #f1f1f1;
                    border-radius: 10px;
                }
                
                div::-webkit-scrollbar-thumb {
                    background: #c1c1c1;
                    border-radius: 10px;
                }
                
                div::-webkit-scrollbar-thumb:hover {
                    background: #a8a8a8;
                }
                `}
            </style>
            <Card>
                <Row justify="space-between" align="middle" style={{ marginBottom: 16 }}>
                    <Col>
                        <Title level={3}>用户管理</Title>
                    </Col>
                    <Col>
                        <Space>
                            <Button
                                type="primary"
                                icon={<PlusOutlined />}
                                onClick={() => navigate('/users/new')}
                            >
                                添加用户
                            </Button>
                        </Space>
                    </Col>
                </Row>

                {error && (
                    <Alert
                        message="数据加载失败"
                        description={error}
                        type="error"
                        showIcon
                        style={{ marginBottom: 16 }}
                    />
                )}

                <Spin spinning={loadingUsers && users.length === 0}>
                    <Table
                        dataSource={users}
                        columns={userColumns}
                        rowKey="id"
                        pagination={false}
                    />
                </Spin>
            </Card>

            {/* 绑定角色对话框 */}
            <Modal
                title={`为用户 ${selectedUser?.username} 绑定角色`}
                open={bindRoleModalVisible}
                onOk={handleSaveUserRoles}
                onCancel={() => setBindRoleModalVisible(false)}
                width={800}
                okText="保存"
                cancelText="取消"
            >
                <Transfer
                    dataSource={roleTransferDataSource}
                    targetKeys={userRoles}
                    onChange={handleRoleTransferChange}
                    render={item => item.title}
                    listStyle={{
                        width: 350,
                        height: 400,
                    }}
                    titles={['可分配角色', '已分配角色']}
                    showSearch
                    filterOption={(inputValue, item) => {
                        return item.title!.indexOf(inputValue) !== -1;
                    }}
                />
            </Modal>

            {/* 绑定权限对话框 */}
            <Modal
                title={`为用户 ${selectedUser?.username} 绑定权限`}
                open={bindAuthorityModalVisible}
                onOk={handleSaveUserAuthorities}
                onCancel={() => setBindAuthorityModalVisible(false)}
                width={800}
                okText="保存"
                cancelText="取消"
            >
                <Transfer
                    dataSource={authorityTransferDataSource}
                    targetKeys={userAuthorities}
                    onChange={handleAuthorityTransferChange}
                    render={item => item.title}
                    listStyle={{
                        width: 350,
                        height: 400,
                    }}
                    titles={['可分配权限', '已分配权限']}
                    showSearch
                    filterOption={(inputValue, item) => {
                        return item.title!.indexOf(inputValue) !== -1;
                    }}
                />
            </Modal>
        </div>
    );
};

export default UserPage;
